package com.sctu.EMSApp;


import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.*;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.*;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.alibaba.fastjson.JSON;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.sctu.bean.UploadReturnInfo;
import com.sctu.http.UrlConfig;
import com.sctu.httpvollry.GetVolleyHttp;
import com.sctu.util.SharePreferenceUtil;
import com.sctu.uttilphoto.activity.AlbumActivity;

import com.sctu.uttilphoto.activity.GalleryActivity;
import com.sctu.uttilphoto.util.*;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;


/**
 * Created by Administrator on 2016/1/5.
 */

public class MyinfoWritenotesAcitvity extends FragmentActivity {

    private View parentView;

    //头部返回按钮
    ImageView headReturnImage;
    //提交按钮
    TextView upload;
    //标题文本
    EditText titleText;
    //内容文本
    EditText contentText;
    //添加图片的加号
    ImageView addPhotoImage;
    //添加poupuwindow
    private PopupWindow popupWindow;
    //popuwindow所属的布局
    private LinearLayout liner_popup;
    //存放图片的gridview
    private GridView noScrollgridview;
    private GridAdapter adapter;

    public static Activity main;

    public static Bitmap bimap ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        main = this;
        Res.init(this);
        bimap = BitmapFactory.decodeResource(
                getResources(),
                R.drawable.write_notes_addphoto);
        super.onCreate(savedInstanceState);
        parentView = getLayoutInflater().inflate(R.layout.activity_myinfo_writenotes, null);
        setContentView(parentView);
        PublicWay.activityList.add(this);
        initview();
    }

    //初始化控件
    @TargetApi(Build.VERSION_CODES.CUPCAKE)
    private void initview() {
        //初始化popuwindow
        popupWindow = new PopupWindow(MyinfoWritenotesAcitvity.this);

        //两个文本输入框
        titleText = (EditText) findViewById(R.id.activity_myinfo_write_travel_notes_titleEdit);
        contentText = (EditText) findViewById(R.id.activity_myinfo_write_travel_notes_contentEdit);

        //返回按钮
        headReturnImage = (ImageView) findViewById(R.id.activity_myinfo_write_travel_returnimage);
        headReturnImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MyinfoWritenotesAcitvity.this.finish();
            }
        });


        //上传按钮
        upload = (TextView) findViewById(R.id.activity_myinfo_write_travel_upload);
        upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                HashMap map = new HashMap();

                String title = titleText.getText().toString();
                String content = contentText.getText().toString();

                if ((title != null && !("".equals(title))) && (content != null && !("".equals(content)))) {
                    map.put("title", title);
                    map.put("content", content);
                    String myName = SharePreferenceUtil.getInstance(MyinfoWritenotesAcitvity.this).getKeyData("username");
                    //String myName = "ren";
                    map.put("author", myName);
                    String userId = SharePreferenceUtil.getInstance(MyinfoWritenotesAcitvity.this).getKeyData("userId");
                    //String uid = "11";
                    map.put("uid", userId);

                    GetVolleyHttp.getInstance(MyinfoWritenotesAcitvity.this).getStringPOSTJsonData(UrlConfig.URL_USER_UPLOADNOTES, map, listener, errorlistener);
                    /**
                     * 添加图片的字节数组
                     */

                } else {
                    Toast.makeText(MyinfoWritenotesAcitvity.this, "内容为空或不完整", Toast.LENGTH_LONG)
                            .show();
                }

            }

            Response.Listener<String> listener = new Response.Listener<String>() {
                @Override
                public void onResponse(String json) {
                    Log.e("json", json);
                    UploadReturnInfo uploadReturnInfo = JSON.parseObject(json, UploadReturnInfo.class);
                    if (uploadReturnInfo.getMsg().equals("success")) {
                        Intent intent = new Intent();
                        intent.setClass(MyinfoWritenotesAcitvity.this, MyinfoWriteNotesSuccessActivity.class);
                        intent.putExtra("id", uploadReturnInfo.getResults().get(0).getId());
                        finish();
                        MyinfoWritenotesAcitvity.this.startActivity(intent);

                    } else {
                        Toast.makeText(MyinfoWritenotesAcitvity.this, "上传失败01", Toast.LENGTH_LONG)
                                .show();
                    }
                }
            };

            // 当网络请求返回状态不成功（也就不是200）
            Response.ErrorListener errorlistener = new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError arg0) {
                    Toast.makeText(MyinfoWritenotesAcitvity.this, "上传失败02", Toast.LENGTH_LONG)
                            .show();
                }
            };
        });

        //获取popupwindow
        View view = getLayoutInflater().inflate(R.layout.activity_myinfo_write_travel_item_popupwindows, null);

        //控制popupwindow的显示方式以及弹出方式
        liner_popup = (LinearLayout) view.findViewById(R.id.activity_myinfo_write_travel_addphoto_liner);

        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setContentView(view);

        //获取添加图片的控件
        final RelativeLayout relat = (RelativeLayout) view.findViewById(R.id.activity_myinfo_write_travel_addphoto_relat);
        ImageView getphotobyphoto = (ImageView) view.findViewById(R.id.activity_myinfo_write_travel_addphoto_byphoto);
        ImageView getphotobycamera = (ImageView) view.findViewById(R.id.activity_myinfo_write_travel_addphoto_by_camera);
        ImageView getphotocancel = (ImageView) view.findViewById(R.id.activity_myinfo_write_travel_addphoto_cancel);


        relat.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                popupWindow.dismiss();
                relat.clearAnimation();
            }
        });
        getphotobycamera.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                photo();
                popupWindow.dismiss();
                relat.clearAnimation();
            }
        });
        getphotobyphoto.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(MyinfoWritenotesAcitvity.this,
                        AlbumActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.activity_translate_in, R.anim.activity_translate_out);
                popupWindow.dismiss();
                relat.clearAnimation();
            }
        });
        getphotocancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                popupWindow.dismiss();
                relat.clearAnimation();
            }
        });






        noScrollgridview = (GridView) findViewById(R.id.activity_myinfo_write_travel_addphotogrid);
        noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));




        adapter = new GridAdapter(this);
        if(Bimp.tempSelectBitmap.size()>0) {
            adapter.update();
        }
        noScrollgridview.setAdapter(adapter);
        noScrollgridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                Log.e("ss","运行");
                if (arg2 == Bimp.tempSelectBitmap.size()) {


                    InputMethodManager m=(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);  //解决输入器没自动关闭情况
                    if(m.isActive()){
                        m.hideSoftInputFromWindow(titleText.getWindowToken(),0);
                        m.hideSoftInputFromWindow(contentText.getWindowToken(),0);
                    }

                    liner_popup.startAnimation(AnimationUtils.loadAnimation(MyinfoWritenotesAcitvity.this, R.anim.activity_translate_in));
                    popupWindow.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);

                } else {
                    Intent intent = new Intent(MyinfoWritenotesAcitvity.this,
                            GalleryActivity.class);
                    intent.putExtra("position", "1");
                    intent.putExtra("ID", arg2);
                    startActivity(intent);
                }
            }
        });




    }



    protected void onRestart() {
        adapter.update();
        super.onRestart();
    }

    private static final int TAKE_PICTURE = 0x000001;

    public void photo() {
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(openCameraIntent, TAKE_PICTURE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_PICTURE:
                if (Bimp.tempSelectBitmap.size() < 4 && resultCode == RESULT_OK) {

                    String fileName = String.valueOf(System.currentTimeMillis());
                    Bitmap bm = (Bitmap) data.getExtras().get("data");
                    FileUtils.saveBitmap(bm, fileName);
                    ImageItem takePhoto = new ImageItem();
                    takePhoto.setBitmap(bm);
                    Bimp.tempSelectBitmap.add(takePhoto);
                }
                break;
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            for(int i=0;i< PublicWay.activityList.size();i++){
                if (null != PublicWay.activityList.get(i)) {
                    PublicWay.activityList.get(i).finish();
                }
            }
            MyinfoWritenotesAcitvity.this.finish();
            Bimp.tempSelectBitmap.clear();
        }
        return true;
    }


    @SuppressLint("HandlerLeak")
    public class GridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        private int selectedPosition = -1;
        private boolean shape;

        public boolean isShape() {
            return shape;
        }

        public void setShape(boolean shape) {
            this.shape = shape;
        }

        public GridAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }

        public void update() {
            loading();
        }

        public int getCount() {
            if(Bimp.tempSelectBitmap.size() == 4){
                return 4;
            }
            return (Bimp.tempSelectBitmap.size() + 1);
        }

        public Object getItem(int arg0) {
            return null;
        }

        public long getItemId(int arg0) {
            return 0;
        }

        public void setSelectedPosition(int position) {
            selectedPosition = position;
        }

        public int getSelectedPosition() {
            return selectedPosition;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.item_published_myinfo_writenotes_addphoto_grida,
                        parent, false);
                holder = new ViewHolder();
                holder.image = (ImageView) convertView
                        .findViewById(R.id.item_grida_image);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            if (position == Bimp.tempSelectBitmap.size()) {
                holder.image.setImageBitmap(BitmapFactory.decodeResource(
                        getResources(), R.drawable.write_notes_addphoto));
                if (position == 4) {
                    holder.image.setVisibility(View.GONE);
                }
            } else {
                holder.image.setImageBitmap(Bimp.tempSelectBitmap.get(position).getBitmap());
            }

            return convertView;
        }

        class ViewHolder {
            public ImageView image;
        }

        Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        adapter.notifyDataSetChanged();
                        break;
                }
                super.handleMessage(msg);
            }
        };

        public void loading() {
            new Thread(new Runnable() {
                public void run() {
                    while (true) {
                        if (Bimp.max == Bimp.tempSelectBitmap.size()) {
                            Message message = new Message();
                            message.what = 1;
                            handler.sendMessage(message);
                            break;
                        } else {
                            Bimp.max += 1;
                            Message message = new Message();
                            message.what = 1;
                            handler.sendMessage(message);
                        }
                    }
                }
            }).start();
        }
    }
}
